package web.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.servlet.dto.DtoFactory;
import data.model.User;

public class ReminderServlet extends AbstractJsonCapableServlet {

    private static final int FIVE_MINUTES_IN_MILLISECONDS = 5 * 60 * 1000;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final User user = dataLayer.findUserByEmail(request.getParameter("email"));
        if (user == null) {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid user"), response);
        } else if (user.getConfirmationToken() != null) {
            jsonHandler.writeAsJson(DtoFactory.createErrorMessage("Invalid user"), response);
        } else if (user.getLastReminder() != null && new Date().getTime() - user.getLastReminder().getTime() < FIVE_MINUTES_IN_MILLISECONDS) {
            jsonHandler
                    .writeAsJson(DtoFactory.createErrorMessage("A reminder email has been sent recently. Please wait at least 5 minutes before retry"), response);
        } else {
            updateLastReminderDate(user);

            sendPasswordEmail(user.getEmail(), user.getPassword());

            jsonHandler.writeAsJson(DtoFactory.createMessage("An email containing your password has been sent to your email address"), response);
        }
    }

    private void updateLastReminderDate(User user) {
        user.setLastReminder(new Date());
        dataLayer.updateObject(user);
    }

    private void sendPasswordEmail(String email, String password) {
        final Map<String, String> mailTemplateParams = new HashMap<String, String>();
        mailTemplateParams.put("password.plainTextPassword", password);
        mailTemplateParams.put("password.loginUrl", HOST + "/index.jsp");

        emailLayer.sendEmail(email, "password.subject", "password.body", mailTemplateParams);
    }
}
